package dao

import (
	"context"
	"errors"
	"forum/app/user/internal/repository/db/model"
	pb "forum/idl/pb/user"
	"forum/pkg/util/logger"
	"gorm.io/gorm"
)

type UserDao struct {
	*gorm.DB
}

func NewUserDao(ctx context.Context) *UserDao {
	return &UserDao{NewDBClient(ctx)}
}

// GetUserInfo 获取用户信息
func (dao *UserDao) GetUserInfo(req *pb.UserRequest) (user *model.User, err error) {
	err = dao.DB.Model(&model.User{}).Where("username = ?", req.UserName).First(&user).Error
	return
}

// CreateUser 创建用户
func (dao *UserDao) CreateUser(req *pb.UserRequest) (err error) {
	var count int64
	dao.DB.Model(&model.User{}).Where("username = ?", req.UserName).Count(&count)
	if count > 0 {
		return errors.New("user already exists")
	}

	user := &model.User{
		Username: req.UserName,
		Nickname: req.NickName,
	}
	_ = user.SetPassword(req.Password)
	err = dao.DB.Model(&model.User{}).Create(&user).Error
	if err != nil {
		logger.LoggersObj.Infoln("Create User Error:" + err.Error())
		return
	}
	return
}

// UpdateUser 更新用户信息
func (dao *UserDao) UpdateUser(req *pb.UserRequest) (err error) {
	user := &model.User{
		Nickname: req.NickName,
		Username: req.UserName,
	}
	_ = user.SetPassword(req.Password)
	err = dao.DB.Model(&model.User{}).Where("username = ?", req.UserName).Updates(&user).Error
	if err != nil {
		logger.LoggersObj.Infoln("Update User Error:" + err.Error())
		return
	}
	return
}

// DeleteUser 删除用户
func (dao *UserDao) DeleteUser(req *pb.UserRequest) (err error) {
	err = dao.DB.Model(&model.User{}).Where("username = ?", req.UserName).Delete(&model.User{}).Error
	return
}
